﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Singer.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singer.Framework.SeedData
{
    /// <summary>
    /// 种子数据
    /// </summary>
    public static class DbSeedDataServiceExtensions
    {
        public static void AddDbSeedData<T>(this IServiceCollection services)
            where T : class, IDbSeedData
        {
            services.AddTransient<IDbSeedData, T>();
        }

        public static void AddDbSeedData(this IServiceCollection services, params Type[] dbSeedDataTypes) 
        {
            foreach (var seedDataType in dbSeedDataTypes)
            {
                if(!typeof(IDbSeedData).IsAssignableFrom(seedDataType))
                    throw new Exception($"【DbSeedData】The Type '{seedDataType.Name}' is not an implementation of 'Singer.Framework.IDbSeedData'.");
                services.AddTransient(typeof(IDbSeedData), seedDataType);
            }
        }

        /// <summary>
        /// 在程序运行时启动一次，初始化数据库种子数据
        /// </summary>
        public static async Task InitDbSeedDataAsync(this IApplicationBuilder app)
        {
            using var scope = app.ApplicationServices.CreateScope();
            IEnumerable<IDbSeedData> seeds = scope.ServiceProvider.GetServices<IDbSeedData>();
            foreach (var seed in seeds)
            {
                try
                {
                    await seed.ExecuteAsync();
                }
                catch (Exception ex)
                {
                    throw new CoreException("初始化数据库种子数据出错，异常信息：" + ex.Message, "dbSeedData");
                }
            }
        }
    }
}
